function [state,options] = psoplotbestf(options,state,flag)
% Plots the best, mean, and worst scores of particle swarm.

notinf = isfinite(state.Score) ;

if strcmp(flag,'init')
    set(gca,'NextPlot','add',...
        'XLabel',xlabel('Generation'),...
        'YLabel',ylabel('Score'))
%     line(state.Generation,max(state.Score),...
%         'Color','red',...
%         'Tag','Worst Scores',...
%         'Marker','.',...
%         'LineStyle','none')
    line(state.Generation,mean(state.Score(notinf)),...
        'Color','blue',...
        'Tag','Mean Scores',...
        'Marker','.',...
        'LineStyle','none')
    line(state.Generation,min(state.Score),...
        'Color','black',...
        'Tag','Best Scores',...
        'Marker','.',...
        'LineStyle','none')
elseif strcmp(flag,'done')
    legend({'Mean Score','Best Score'})
else
%     hworst = findobj(gca,'Tag','Worst Scores','Type','line') ;
    hmean = findobj(gca,'Tag','Mean Scores','Type','line') ;
    hbest = findobj(gca,'Tag','Best Scores','Type','line') ;
    x = [get(hmean,'XData'), state.Generation] ;
%     yworst = [get(hworst,'YData'), max(state.Score)] ;
    ymean = [get(hmean,'YData'), mean(state.Score(notinf))] ;
    ybest = [get(hbest,'YData'), min(state.Score)] ;
%     set(hworst,...
%         'XData',x,...
%         'YData',yworst)
    set(hmean,...
        'XData',x,...
        'YData',ymean)
    set(hbest,...
        'XData',x,...
        'YData',ybest)
    titletxt = sprintf('Best: %g Mean: %g',ybest(end),ymean(end)) ;
    title(titletxt)
end